package com.himore.api.web.controller.system;

import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.himore.api.common.constant.UserConstants;
import com.himore.api.common.core.redis.RedisCache;
import com.himore.api.common.utils.*;
import com.himore.api.system.service.ISysUserService;
import com.himore.api.web.enums.TaskIdEnum;
import com.himore.api.web.model.TSelectedAwards;
import com.himore.api.web.model.TTaskCompleteInfo;
import com.himore.api.web.model.WxLoginVO;
import com.himore.api.web.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.himore.api.common.constant.Constants;
import com.himore.api.common.core.domain.AjaxResult;
import com.himore.api.common.core.domain.entity.SysMenu;
import com.himore.api.common.core.domain.entity.SysUser;
import com.himore.api.common.core.domain.model.LoginBody;
import com.himore.api.common.core.domain.model.LoginUser;
import com.himore.api.web.framework.web.service.SysLoginService;
import com.himore.api.web.framework.web.service.SysPermissionService;
import com.himore.api.web.framework.web.service.TokenService;
import com.himore.api.system.service.ISysMenuService;

import javax.annotation.Resource;

import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidParameterSpecException;
import java.util.concurrent.TimeUnit;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpSession;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.codehaus.xfire.util.Base64;
import org.springframework.web.bind.annotation.RequestBody;


/**
 * 登录验证
 * 
 * @author dongwang
 */
@Api(tags = "登录验证管理")
@RestController
public class SysLoginController{


    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Resource
    private HttpAPIService httpAPIService;

    @Autowired
    private HttpSession session;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ITTaskCompleteInfoService tTaskCompleteInfoService;

    @Autowired
    private ITSysGiftsService tSysGiftsService;

    @Autowired
    private ITSysTaskService tSysTaskService;
    @Autowired
    private ITSelectedAwardsService tSelectedAwardsService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation(value = "登录接口", notes = "登录接口", produces = "application/json")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody){
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(),"");
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }


    @Autowired
    private RedisCache redisCache;


    /**
     * 获取微信登录相关信息
     *
     * @return 用户信息
     */
    @PostMapping("wxCode")
    public AjaxResult wxCode(@RequestBody WxLoginVO vo){
        System.out.println("wxCode传的参数为 ==="+vo.toString());
        if(StringUtils.isBlank(vo.getCode())){
            return  AjaxResult.error(ErrorCodeUtil.E_220,"您输入的code为空，请重新输入！ ");
        }
        Map  result= new HashMap();
        String  res ="";
        Map  param = new HashMap();
        param.put("appid",UserConstants.WX_APPID);
        param.put("secret",UserConstants.WX_APP_SECRET);
        param.put("js_code",vo.getCode());
        param.put("grant_type",UserConstants.WX_GRANT_TYPE);
       try{
            res = httpAPIService.doGet(UserConstants.WX_LOGIN_URL,param);
        }catch (Exception e){
            e.printStackTrace();
            return  AjaxResult.error(ErrorCodeUtil.E_500,res);
        }
        JSONObject jsonObject = JSONObject.parseObject(res);
        String  errorCode = jsonObject.getString("errcode");
        String errmsg = jsonObject.getString("errmsg");
        if(StringUtils.isNotBlank(errorCode)){
            return  AjaxResult.error(ErrorCodeUtil.E_220,"请求微信数据异常，"+errmsg);
        }
        String sessionKey = jsonObject.getString("session_key");
        if(StringUtils.isBlank(sessionKey)){
            return  AjaxResult.error(ErrorCodeUtil.E_220,"通过code获取的sessionKey为空，请重新输入！");
        }
        String  codeKey ="";
        if(StringUtils.isBlank(vo.getCodeKey())){
            codeKey = CommonUtils.generateCodeKey();
        }else{
            codeKey = vo.getCodeKey();
        }
        //获取sessionKey以后,存入到redis 中， key是 获取的或者是 传过来的 。
        redisCache.setCacheObject(codeKey, sessionKey, Constants.CODE_EXPIRATION, TimeUnit.MINUTES);
        Map ret = new HashMap();
        ret.put("codeKey",codeKey);
        System.out.println("返回的codekey为== "+ codeKey);
        return  AjaxResult.success(ret);
    }



    /**
     * 获取微信登录相关信息
     *
     * @return 用户信息
     */
    @PostMapping("wxLogin")
    public AjaxResult getWXLoginSessionInfo(@RequestBody WxLoginVO vo){
      /*  属性	类型	默认值	必填	说明
        appid	string		是	小程序 appIdi
        secret	string		是	小程序 appSecret
        js_code	string		是	登录时获取的 code
        grant_type	string		是	授权类型，此处只需填写 authorization_code
        */
        System.out.println(vo.toString());
        if(StringUtils.isBlank(vo.getEncryptedData())){
            return  AjaxResult.error(ErrorCodeUtil.E_220,"您输入的待解码数据为空，请重新输入！");
        }
        if(StringUtils.isBlank(vo.getOffset())){
            return  AjaxResult.error(ErrorCodeUtil.E_220,"您输入的偏移量数据为空，请重新输入！");
        }
        if(StringUtils.isBlank(vo.getCodeKey())){
            return  AjaxResult.error(ErrorCodeUtil.E_220,"您输入的codeKey为空，请重新输入！");
        }
        //请求返回值
        Map  result= new HashMap();
        String avatarUrl = "";
        String  res ="";
            String sessionKey = redisCache.getCacheObject(vo.getCodeKey());
            if(StringUtils.isBlank(sessionKey)){
                return  AjaxResult.error(ErrorCodeUtil.E_407,"sessionKey为空，请重新进入小程序！");
            }
            System.out.println("解密出来的sessionKey == "+ sessionKey);
            //存表操作
            JSONObject object= new  JSONObject();
            try {
                 object= getUserInfo(vo.getEncryptedData(),sessionKey,vo.getOffset());
                 if(null== object){
                     return  AjaxResult.error(ErrorCodeUtil.E_407,"解密用户数据异常，请联系管理员！");
                 }
            }catch (Exception e){
                e.printStackTrace();
                return  AjaxResult.error(ErrorCodeUtil.E_407,"解密用户数据异常，请联系管理员！");
            }
            try {
                //String nickName = object.getString("nickName");
                String openid = object.getString("openId");
                String unionid = object.getString("unionId");
                String  gender = object.getString("gender");
                avatarUrl = object.getString("avatarUrl");

                AjaxResult ajax = AjaxResult.success();
                //ajax.put("result",object);
                SysUser resUser = sysUserService.selectUserByUserName(openid);
                //如果根据用户的手机号查询不出来
                if(StringUtils.isNull(resUser)){
                    SysUser user = new SysUser();
                    user.setUserName(openid);
                    user.setPassword(SecurityUtils.encryptPassword(openid));
                    user.setNickName(vo.getNickName());
                    user.setAvatar(vo.getAvatarUrl());
                    user.setOpenId(openid);
                    user.setUnionId(unionid);
                    user.setSex(gender);
                    user.setAvatar(avatarUrl);
                    user.setUserIdentifNum(CommonUtils.generateUserIdentiNum());
                    user.setReplenishSign(0);
                    System.out.println("创建用户的参数=="+user.toString());
                    boolean flag=false;
                    if(null!=vo.getInvitedNum() ){
                        user.setInvitedNum(vo.getInvitedNum());
                        flag=true;
                    }
                    //如果邀请码不为空 ，则 为
                    if(flag ){
                        SysUser users = new SysUser();
                        users.setUserIdentifNum(vo.getInvitedNum());
                        List<SysUser> userList =sysUserService.selectUserList(users);
                        SysUser  inviteUser = null;
                        if(null!= userList && userList.size()>0){
                            inviteUser= userList.get(0);
                        }
                        if(null!=inviteUser){
                            //查看，用户的创建时间为本周内且邀请码为 当前用户的邀请码的用户的数量
                            Map<String, Date> params = CommonUtils.getWeekDate();
                            Date signBeginDate = params.get("mondayDate");
                            Date signEndDate = params.get("sundayDate");
                            signEndDate = DateUtils.addTimeTodate(signEndDate,1);
                            SysUser sysUser  = new SysUser();
                            sysUser.setSigndateBegin(DateUtils.getYYYYMMDDDate(signBeginDate));
                            sysUser.setSigndateEnd(DateUtils.getYYYYMMDDDate(signEndDate));
                            sysUser.setInvitedNum(vo.getInvitedNum());
                            int count = sysUserService.selectUserCountByInviteNum(sysUser);
                            List<SysUser> users1 = sysUserService.selectUserList(sysUser);
                            if( count==2 ){
                                TTaskCompleteInfo completeInfo = new TTaskCompleteInfo();
                                completeInfo.setUserId(inviteUser.getUserId());
                                completeInfo.setTaskId(TaskIdEnum.TASK_1.getValue());
                                completeInfo.setCreateTime(DateUtils.getNowDate());
                                tTaskCompleteInfoService.insertTTaskCompleteInfo(completeInfo);
                                //个人需要增加的补签
                                SysUser us = new SysUser();
                                us.setUserId(inviteUser.getUserId());
                                us.setReplenishSign(1);
                                us.setScore(50);
                                sysUserService.updateScoreOrDrawInfo(us);
                            }
                        }
                    }
                    sysUserService.insertUser(user);
                }else{
                    SysUser userInfo = new SysUser();
                    userInfo.setUserId(resUser.getUserId());
                    if(StringUtils.isNotBlank(vo.getNickName())){
                        userInfo.setNickName(vo.getNickName());
                    }
                    if(StringUtils.isNotBlank(vo.getAvatarUrl())){
                        userInfo.setAvatar(vo.getAvatarUrl());
                    }
                    sysUserService.updateUser(userInfo);
                }
                // 生成令牌
                String token = loginService.login(openid, openid, openid,"",openid);
                ajax.put("token",token);
                ajax.put("avatarUrl",avatarUrl);
                return ajax;
            }catch ( Exception e){
                e.printStackTrace();
                return  AjaxResult.error(ErrorCodeUtil.E_500,"用户登录系统异常，原因为："+e.getMessage());
            }
    }


    /**
     * 获取微信登录相关信息
     *
     * @return 用户信息
     */
    @PostMapping("simpleWxLogin")
    public AjaxResult getWXLoginSessionInfo(@RequestParam String  phoneNum){

        try {
            String purePhoneNumber = phoneNum;

            SysUser resUser = sysUserService.selectUserByUserName("wx-"+purePhoneNumber);
            //如果根据用户的手机号查询不出来
            if(StringUtils.isNull(resUser)){
                SysUser user = new SysUser();
                user.setUserName("wx-"+purePhoneNumber);
                user.setPassword(SecurityUtils.encryptPassword(purePhoneNumber));
                user.setPhonenumber(purePhoneNumber);
                user.setNickName("nick-"+purePhoneNumber);
                user.setUserIdentifNum(CommonUtils.getStringRandom(25));
                sysUserService.insertUser(user);
            }
            AjaxResult ajax = AjaxResult.success();
            // 生成令牌
            String token = loginService.login("wx-"+purePhoneNumber, purePhoneNumber, purePhoneNumber,"",purePhoneNumber);
            ajax.put("token",token);
            ajax.put("phoneNum",purePhoneNumber);
            return ajax;
        }catch ( Exception e){
            e.printStackTrace();
            return  AjaxResult.error(ErrorCodeUtil.E_500,"用户登录系统异常，原因为："+e.getMessage());
        }
    }


    /**
     * 保存头像信息
     *
     * @return 用户信息
     */
    @ApiOperation(value = "保存头像信息", notes = "保存头像信息", produces = "application/json")
    @PostMapping("saveAvarInfo")
    public AjaxResult saveAvarInfo(@RequestBody WxLoginVO vo  ){
        try {
            SysUser sysUser = SecurityUtils.getLoginUser().getUser();
            sysUser.setAvatar(vo.getAvatarUrl());
            sysUser.setNickName(vo.getNickName());
            sysUserService.updateUser(sysUser);
            return AjaxResult.success();
        }catch ( Exception e){
            e.printStackTrace();
            return  AjaxResult.error(ErrorCodeUtil.E_500,"用户登录系统异常，原因为："+e.getMessage());
        }
    }




    /**
     * 获取微信登录相关信息
     *
     * @return 用户信息
     */
    //@GetMapping("wxLogin")
    public AjaxResult WxLogin(@RequestParam(value = "encryptedData",required = false) String  encryptedData,
                              @RequestParam("phoneNum") String phoneNum,
                               @RequestParam("offset") String  offset,
                               @RequestParam("status") String  status){
        String  sessionKey = "";
        if(StringUtils.isNotNull(session.getAttribute("sessionKey"))){
            sessionKey =session.getAttribute("sessionKey").toString();
        }
        if("0".equals(status)){
            try {
             JSONObject object=   getUserInfo(encryptedData,sessionKey,offset);
             System.out.println(object.toJSONString());
             return  AjaxResult.success(object);
            }catch (Exception e){
                e.printStackTrace();
                return  AjaxResult.error(ErrorCodeUtil.E_500,e.getMessage());
            }
        }else{
            return AjaxResult.success();
        }
    }


    /**
     * 获取信息
     */
    public  static  JSONObject getUserInfo(String encryptedData,String sessionkey,String iv){
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionkey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取微信登录相关信息
     *
     * @return 用户信息
     */
    @GetMapping("/getAwardsInfoByPhoneNum")
    public AjaxResult getAwardsInfoByPhoneNum(@RequestParam("phoneNum") String phoneNum){
            if(StringUtils.isBlank(phoneNum)){
                return AjaxResult.error(ErrorCodeUtil.E_220,"您输入的手机号为空，请重新输入！");
            }
            if(!CommonUtils.checkIsPhoneNum(phoneNum)){
                return AjaxResult.error(ErrorCodeUtil.E_220,"您输入的手机号格式错误，请重新输入！");
            }

            SysUser sysUser = new SysUser();
            sysUser.setPhonenumber(phoneNum);
            List<SysUser> user = sysUserService.selectUserList(sysUser);
            SysUser sysUser1 = user.get(0);
            if(null == user || user.size()==0){
                return AjaxResult.error(ErrorCodeUtil.E_220,"通过手机号查询不到用户信息，请提示用户完善手机号信息！");
            }
            TSelectedAwards selectedAwards =new TSelectedAwards();
            selectedAwards.setUserId(sysUser1.getUserId());
            List<TSelectedAwards> list = tSelectedAwardsService.selectTSelectedAwardsListByPhone(selectedAwards);


            return AjaxResult.success(list);

    }




}
